<template>
  <div class="app-project">
    <el-row>
      <el-col :span="24">
        <dynForm :info-form="infoForm" :search-tags="searchTags">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="doSearch"
          >
            {{ $t("search") }}</el-button
            >
        </dynForm>
      </el-col>
    </el-row>
    <!--工具栏-->
    <div class="table-buttons">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="switchHandle('add')"
      >{{ $t("add") }}</el-button
      >
      <el-button
        :disabled="UpdateDisabled"
        type="primary"
        icon="el-icon-edit"
        @click="switchHandle('modify')"
      >{{ $t("modify") }}</el-button
      >
      <el-button
        :disabled="DeleteDisabled"
        type="danger"
        icon="el-icon-delete"
        @click="switchHandle('del')"
      >{{ $t("delete") }}</el-button
      >
    </div>
    <!-- 主体部分 -->
    <el-card class="box-card" shadow="never">
      <!-- 表单部分 -->
      <el-row :gutter="15">
        <el-col
          :xs="24"
          :sm="24"
          :md="18"
          :lg="18"
          :xl="18"
          style="margin-bottom: 10px"
        >
          <dynTable
            ref="dynTable"
            :loading="tableLoading"
            :table-data="tableData"
            :table-columns="tableColumns"
            :handle-selection-change="handleSelectionChange"
            :row-click="rowClick"
          />
          <!--分页组件-->
          <pagination
            :total="total"
            :page.sync="listQuery.page"
            :size.sync="listQuery.size"
            @pagination="getList"
          />
        </el-col>
        <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
          <el-card class="box-card" shadow="never">
            <div slot="header" class="clearfix">
              <el-tooltip
                :content="$t('proejectMenuAssignment')"
                class="item"
                effect="dark"
                placement="top"
              >
                <span style="float: left; padding: 6px 9px; fontSize: 14px">{{ $t("menuAssignment") }}</span>
              </el-tooltip>
              <el-button
                :disabled="!showButton"
                :loading="menuLoading"
                icon="el-icon-check"
                style="float: right; padding: 6px 9px"
                type="primary"
                @click="saveMenu"
              >{{ $t("save") }}</el-button
              >
            </div>
            <div class="tree-box">
              <el-tree
                ref="menu"
                :data="menus"
                :default-checked-keys="checkedKeys"
                :props="defaultProps"
                check-on-click-node
                check-strictly
                show-checkbox
                node-key="id"
                @check="checkChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    <!-- 弹窗组件 -->
    <myDialog ref="myDialog" @initList="initList"/>
  </div>
</template>

<script>
import crudProjects from '@/api/system/project'
import { getMenusTree } from '@/api/system/menu'
import myDialog from './module/form'
import mySetting from '@/mixins/mySetting'
import networkTips from '@/mixins/networkTips'
import { clearNull } from '@/utils/myTools'
export default {
  name: 'ProjectPage',
  components: {
    myDialog
  },
  mixins: [mySetting, networkTips],
  data() {
    return {
      defaultProps: { children: 'children', label: 'label', isLeaf: 'leaf' },
      menuLoading: false,
      showButton: false,
      tableLoading: true,
      menus: [],
      checkedKeys: [],
      menuIds: [],
      multipleSelection: [],
      UpdateDisabled: true,
      DeleteDisabled: true,
      infoForm: {},
      searchTags: [
        { label: this.$t('keyword'), prop: 'name', tag: 'DynInput' }
      ],
      tableColumns: [
        { prop: '', label: '', type: 'selection' },
        { prop: '', label: this.$t('index'), type: 'index', width: '50px', templete: (_scope) => {
          return (
            <span>{ (this.listQuery.page - 1) * this.listQuery.size + _scope.$index + 1 }</span>
          )
        } },
        {
          prop: 'code',
          label: this.$t('projectCode')
        },
        {
          prop: 'name',
          label: this.$t('projectName')
        },
        {
          prop: 'admin',
          label: this.$t('adminAccount')
        },
        {
          prop: 'manager',
          label: this.$t('manager')
        },
        {
          prop: 'description',
          label: this.$t('description')
        },
        {
          prop: 'status',
          label: this.$t('status'),
          templete: (_scope) => {
            return (
              <el-switch
                v-model={_scope.row.enabled}
                active-color='#13ce66'
                inactive-color='#ff4949'
                on-change={() => this.changeEnabled(_scope.row)}
              />
            )
          }
        },
        {
          prop: 'createTime',
          label: this.$t('createTime'),
          width: '165px'
        }
      ],
      job_status: [
        { key: 0, display_name: this.$t('disenabled') },
        { key: 1, display_name: this.$t('enabled') }
      ]
    }
  },
  created() {
    this.initList()
    this.initTree()
  },
  methods: {
    switchHandle(val) {
      switch (val) {
        case 'add':
          this.handleClickAdd()
          break
        case 'del':
          this.handleDel()
          break
        case 'modify':
          this.modify()
          break
        default:
          break
      }
    },
    // 新增数据
    handleClickAdd() {
      this.$refs.myDialog.openDialog()
    },
    // 删除数据
    handleDel() {
      this.$confirm(
        this.$t('confirmDelete') +
          this.multipleSelection.length +
          this.$t('recordCount'),
        this.$t('tip'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      ).then(() => {
        const ids = this.multipleSelection.map((ele) => {
          return ele.id
        })
        crudProjects.del({ ids: ids }).then((res) => {
          this.netTips(res, this.setOnePage, this.initList)
        })
      })
    },
    // 修改数据
    modify() {
      this.$refs.myDialog.openDialog(this.multipleSelection[0])
    },
    // 切换分页
    getList(page) {
      this.listQuery = page
      this.initList()
    },
    // 初始化列表
    initList() {
      let obj = {
        ...this.listQuery,
        ...this.infoForm
      }
      obj = clearNull(obj)
      crudProjects.getList(obj).then((res) => {
        this.tableData = res.data
        this.total = res.total
        this.tableLoading = false
      })
    },
    // 点击查询
    doSearch() {
      this.listQuery.page = 1
      this.initList()
    },
    handleSelectionChange(row) {
      this.multipleSelection = row
    },
    rowClick(row) {
      this.$refs.dynTable.$refs.multipleTable.clearSelection()
      this.$refs.dynTable.$refs.multipleTable.toggleRowSelection(row)
      this.handleCurrentChange(row)
    },
    changeEnabled(data) {
      const newstatus = data.enabled === false ? 0 : 1
      this.$confirm(
        this.$t('confirmFirst') +
          this.job_status[newstatus].display_name +
          '' +
          data.name +
          this.$t('confirmSecond'),
        this.$t('tip'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          var param = { id: data.id, status: newstatus }
          crudProjects
            .changestatus(JSON.stringify(param))
            .then((res) => {
              this.$betterTips(res)
            })
            .catch(() => {
              data.enabled = !data.enabled
            })
        })
        .catch(() => {
          data.enabled = !data.enabled
        })
    },
    // 初始化tree
    initTree() {
      getMenusTree({ pid: 0 }).then(res => {
        this.menus = res.data
      })
    },
    // 触发单选
    handleCurrentChange(row) {
      this.$refs.menu.setCheckedKeys([])
      crudProjects.getMenuIdsByProjectId({ id: row.id }).then((res) => {
        const checked = res.data.filter(v => !v.isHalf).map(c => c.id)
        this.checkedKeys = checked
      })
      this.showButton = true
    },
    // 保存菜单
    saveMenu() {
      this.menuLoading = true
      // 是半选
      const halfs = this.$refs.menu.getHalfCheckedKeys().map(v => ({ id: v, isHalf: 1 }))
      // 不是半选
      const menus = this.$refs.menu.getCheckedKeys().map(v => ({ id: v, isHalf: 0 }))
      crudProjects.editProjectMenu({ id: this.multipleSelection[0].id,
        menus: [...halfs, ...menus]
      }).then((res) => {
        this.menuLoading = false
        this.$betterTips(res)
      })
    },
    checkChange(data) {
      if (this.checkedKeys.includes(data.id)) {
        const child = [data.id].concat(this.flatten(data.children))
        for (let i = 0; i < child.length; i++) {
          const index = this.checkedKeys.indexOf(child[i])
          if (index !== -1) {
            this.checkedKeys.splice(index, 1)
          }
        }
      } else {
        const child = [data.id].concat(this.flatten(data.children))
        for (let i = 0; i < child.length; i++) {
          const index = this.checkedKeys.indexOf(child[i])
          if (index === -1) {
            this.checkedKeys.push(child[i])
          }
        }
      }
      this.$refs.menu.setCheckedKeys(this.checkedKeys)
    },
    flatten(tree) {
      return (tree || []).reduce((total, current) => {
        const { children, id } = current
        return total.concat(id, this.flatten(children))
      }, [])
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/defaultStyle.scss";
.app-project{
  padding-bottom: 33px;
}
.app-project .el-row:nth-child(1) {
  padding-bottom: 0;
}
.tree-box{
  height: 600px;
  overflow-y: auto;
}
</style>
